package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.ProductBean;
import com.project.bean.SaleCarBean;
import com.project.mapper.IProductMapper;
import com.project.mapper.ISaleCarMapper;
import com.project.service.ISaleCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SaleCarServiceImpl implements ISaleCarService {
    @Autowired
    private ISaleCarMapper saleCarMapper;
    @Autowired
    private IProductMapper productMapper;

    @Override
    public void add(Integer productId,Integer loginUserId) {
        //通过商品id 查询销售车中是否有该商品对象
        SaleCarBean saleCar=saleCarMapper.findByProductId(productId);
        if (saleCar==null){
            //销售车没有该商品，添加销售车商品，数量默认为0,出库以后修改订单数量为出库数量
            saleCarMapper.insert(new SaleCarBean(productId,1,loginUserId));
        }else{
            //销售车有该商品，数量加1
            saleCar.setNum(saleCar.getNum()+1);
            saleCarMapper.updateById(saleCar);
        }
    }

    @Override
    public void updateNumById(Integer saleCarId, Integer newNum) {
        SaleCarBean saleCar=saleCarMapper.selectById(saleCarId);
        saleCar.setNum(newNum);
        saleCarMapper.updateById(saleCar);
    }

    @Override
    public void delById(Integer saleCarId) {
        saleCarMapper.deleteById(saleCarId);
    }

    @Override
    public void delByUser(Integer userId) {
        QueryWrapper qw=new QueryWrapper<>();
        qw.eq("fk_userId",userId);
        saleCarMapper.delete(qw);
    }

    @Override
    public List<SaleCarBean> findByUserId(Integer userId) {
        QueryWrapper<SaleCarBean> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("fk_userId", userId);
        List<SaleCarBean> saleCarList=saleCarMapper.selectList(queryWrapper);
        for (SaleCarBean saleCar:saleCarList){
            saleCar.setProduct(productMapper.selectById(saleCar.getProductId()));
        }
        return saleCarList;
    }

    @Override
    public SaleCarBean findByProductId(Integer productId) {
        QueryWrapper<SaleCarBean> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fk_productId", productId);
        return saleCarMapper.selectOne(queryWrapper);
    }
}
